﻿using Furion.DependencyInjection;
using Furion.FriendlyException;

namespace EMC.VISITOR.Core;
/// <summary>
/// 队列发布服务
/// </summary>
[ApiDescriptionSettings( Order = 100)]
public partial class SysMqPublishService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SysMqPublish> _rep;
    public SysMqPublishService(SqlSugarRepository<SysMqPublish> rep)
    {
        _rep = rep;
    }
    #region 代码生成
    /// <summary>
    /// 分页查询队列发布
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<SysMqPublishOutput>> Page(SysMqPublishInput input)
    {
        var query= _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.User.Contains(input.SearchKey.Trim())
                || u.RoutingKeys.Contains(input.SearchKey.Trim())
                || u.Payload.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.ASoleId), u => u.ASoleId == input.ASoleId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.User), u => u.User.Contains(input.User.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RoutingKeys), u => u.RoutingKeys.Contains(input.RoutingKeys.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Payload), u => u.Payload.Contains(input.Payload.Trim()))
        .WhereIF(input.HandlerResult.HasValue, u => u.HandlerResult == input.HandlerResult)
            .Select<SysMqPublishOutput>()
;
        // query = query.OrderBuilder(input, "", "CreateTime");
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加队列发布
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task Add(AddSysMqPublishInput input)
    {
        var entity = input.Adapt<SysMqPublish>();
        await _rep.InsertAsync(entity);
    }

    /// <summary>
    /// 删除队列发布
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteSysMqPublishInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        // await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新队列发布
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateSysMqPublishInput input)
    {
        var entity = input.Adapt<SysMqPublish>();
        await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
    }

    /// <summary>
    /// 获取队列发布
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<SysMqPublish> Get([FromQuery] QueryByIdSysMqPublishInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 获取队列发布列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<SysMqPublishOutput>> List([FromQuery] SysMqPublishInput input)
    {
        return await _rep.AsQueryable().Select<SysMqPublishOutput>().ToListAsync();
    }





    /// <summary>
    /// 导出队列发布
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Export"), NonUnify]
    public async Task<IActionResult> Export(SysMqPublishInput input)
    {
        var query= _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.User.Contains(input.SearchKey.Trim())
                || u.RoutingKeys.Contains(input.SearchKey.Trim())
                || u.Payload.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.ASoleId), u => u.ASoleId == input.ASoleId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.User), u => u.User.Contains(input.User.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RoutingKeys), u => u.RoutingKeys.Contains(input.RoutingKeys.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Payload), u => u.Payload.Contains(input.Payload.Trim()))
        .WhereIF(input.HandlerResult.HasValue, u => u.HandlerResult == input.HandlerResult)
            .Select<ExportImportSysMqPublishDto>()
;
        var list=await query.ToListAsync();
        IExcelExporter excelExporter = new ExcelExporter();
        var res = await excelExporter.ExportAsByteArray(list);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "队列发布.xlsx" };
    }

     /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<JRResult<string>> Import(IFormFile file)
    {
        bool succeeded = true;
        string message = string.Empty;
        IImporter Importer = new ExcelImporter();
        var importData = await Importer.Import<ExportImportSysMqPublishDto>(file.OpenReadStream());
        if (importData.HasError == true) { succeeded = false; message += "导入错误！"; }
        if (importData.Exception != null) { succeeded = false; message += importData.Exception.ToString(); }
        if (importData.RowErrors.Count > 0) { succeeded = false; message += JSON.Serialize(importData.RowErrors); }
        if (importData.Data == null) { succeeded = false; message += "导入的数据量不能为空！"; }
        if (importData.Data.Count <= 0) { succeeded = false; message += "导入的数据量为0个！"; }
        if (succeeded)
        {
            var models = importData.Data.Adapt<List<SysMqPublish>>();
            await _rep.AsInsertable(models).ExecuteCommandAsync();
        }
        return new JRResult<string>
        {
            Code = succeeded ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = succeeded ? "导入成功！" : message,
            Result = null,
            Type = succeeded ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }


    /// <summary>
    /// 模板下载
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> TemplateDown()
    {
        IImporter Importer = new ExcelImporter();
        var template = await Importer.GenerateTemplateBytes<ExportImportSysMqPublishDto>();
        return new FileStreamResult(new MemoryStream(template), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "队列发布导入模板.xlsx" };
    }
#endregion
}

